
from fastapi import FastAPI,APIRouter,Request
from json.decoder import JSONDecodeError
import requests
import sys 
import uuid
sys.path.append('..')
from utils import videos as F 
from utils import aichat as A
from utils.http_response import HttpResponse 
from utils.db import engine
from minio import Minio
router = APIRouter(prefix="/videos",tags=["videos"])


ak = "jBEqfAG6lAUMYqhf9ZuQ"
sk = 'zzh0117.'
client = Minio(
    "113.31.110.212:9000",
    secure=False,
    access_key=ak,
    secret_key=sk,
)
@router.post("/get_one")
async def get_one(req:Request):
    resp = HttpResponse(code=200,message="success",data=[])
    try:
        body = await req.json()
    except Exception as JSONDecodeError:
        resp.message = "json decode error"
        resp.code = 500
        return resp 
    resp.data = F.select_by_col(engine,body)
    return resp

@router.post("/update_one")
async def update_one(req:Request):
    resp = HttpResponse(code=200,message="success",data=[])
    try:
        body = await req.json()
    except Exception as JSONDecodeError:
        resp.message = "json decode error"
        resp.code = 500
        return resp 
    resp.data = F.update_one(engine,body["cond"],body["item"])  
    return resp 

@router.post("/delete_one")
async def delete_one(req:Request):
    resp = HttpResponse(code=200,message="success",data=[])
    try:
        body = await req.json()
    except Exception as JSONDecodeError:
        resp.message = "json decode error"
        resp.code = 500
        return resp 
    resp.data = F.delete_one(engine,body)  
    return resp 



@router.post("/add_one")
async def add_one(req:Request):
    resp = HttpResponse(code=200,message="success",data=[])
    try:
        body = await req.json()
    except Exception as JSONDecodeError:
        resp.message = "json decode error"
        resp.code = 500
        return resp 
    resp.data = F.add_one(engine,body)  
    return resp 



@router.post("/upload_video")
async def upload_video(req:Request):
    form_data = await req.form()
    # name,file = form_data
    print(form_data)
    uploaded_file = form_data['file']
    filename = uploaded_file.filename
    contents = await uploaded_file.read()
    suffix = filename.split('.')[-1]
    filename = str(uuid.uuid1()) + '.' + suffix
    bucket_name = "foodsite"
    with open('./tmp/'+filename,'wb') as f:
        f.write(contents)
    try:
        client.fput_object(bucket_name,filename,'./tmp/'+filename)
    except Exception  as e : 
        print(e)
    return {"code":200,"message":"success","data":f"http://113.31.110.212:9000/foodsite/{filename}"}


@router.post("/ai_chat")
async def ai_chat(req:Request):
    resp = HttpResponse(code=200,message="success",data=[])
    try:
        body = await req.json()
    except Exception as JSONDecodeError:
        resp.message = "json decode error"
        resp.code = 500
        return resp 
    payload= {
        "messages":[
            {
                "role":'system',
                "content":"you are good at math problem pls help me with this. YOU ARE ONLY ALLOWED TO REPLY MATH PROBLEM AND REFUSE TO ANSWER OTHERS!!!!!!!!."
            },   
            {
                "role":'user',
                "content": 'problem is ' + body["new_message"],
            }             
            ],
            "model":"vicuna-13b-v1.5-16k"
    }
    response = requests.post("http://113.31.110.212:7001/v1/chat/completions",json=payload)
    res = response.json()['choices'][0]['message']['content']
    A.add_one(engine,{"content":body["new_message"],"reserve_1":res})
    print(res)
    resp.data = res
    return resp